package com.sky.sky_server.service.impl;

import java.time.LocalDate;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sky.sky_pojo.dto.BusinessDataVO;
import com.sky.sky_pojo.dto.DishOverViewVO;
import com.sky.sky_pojo.dto.OrderOverViewVO;
import com.sky.sky_pojo.dto.SetmealOverViewVO;
import com.sky.sky_server.mapper.DishMapper;
import com.sky.sky_server.mapper.OrderMapper;
import com.sky.sky_server.mapper.SetmealMapper;
import com.sky.sky_server.mapper.UserMapper;
import com.sky.sky_server.service.WorkSpaceService;

@Service
public class WorkSpaceServiceImpl implements WorkSpaceService{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询订单管理数据
     */
    @Override
    public OrderOverViewVO overviewOrders() {
        return orderMapper.overviewOrders();
    }

    /**
     * 查询菜品总览
     */
    @Override
    public DishOverViewVO overviewDishes() {
        return dishMapper.overviewDishes();
    }

    /**
     * 查询套餐总览
     */
    @Override
    public SetmealOverViewVO overviewSetmeals() {
        return setmealMapper.overviewSetmeals();
    }

    /**
     * 查询起止时间的运营数据
     */
    @Override
    public BusinessDataVO businessData(LocalDate begin, LocalDate end) {
        BusinessDataVO businessDataVO = new BusinessDataVO();

        List<Integer> users = userMapper.userStatistics(begin, end.atTime(23,59,59));
        if(users != null){
            // 获取今日新增用户数
            businessDataVO.setNewUsers(users.get(0));
        }
        
        // 获取有效订单数和订单完成率
        List<Integer> orderTotal = orderMapper.orderStatisticsDailyTotal(begin, end.atTime(23,59,59));
        List<Integer> orderVailded = orderMapper.orderStatisticsDailyValid(begin, end.atTime(23,59,59));
        if(orderTotal != null && orderVailded != null){
            // 获取订单完成率
            Double orderTotaldouble = Double.valueOf(orderTotal.get(0));
            Double orderVaildedDouble = Double.valueOf(orderVailded.get(0));
            Double orderCompletionRate = orderTotaldouble == 0 ? 0 : orderVaildedDouble / orderTotaldouble;
            businessDataVO.setOrderCompletionRate(orderCompletionRate);
            businessDataVO.setValidOrderCount(orderVailded.get(0));
        }

        // 获取营业额
        List<Double> turnOver = orderMapper.turnoverStatistics(begin, end.atTime(23,59,59));
        if(turnOver != null){
            businessDataVO.setTurnover(turnOver.get(0));
        }

        // 平均客单价平均客单价 = 营业额 ÷ 有效订单数
        if(turnOver != null && orderVailded != null){
            Double averagePerOrder = orderVailded.get(0) == 0 ? 0 : turnOver.get(0).doubleValue() / orderVailded.get(0);
            businessDataVO.setUnitPrice(averagePerOrder);
        }

        return businessDataVO;

    }
}
